﻿namespace EFS.Common.Serialization
{
	public static class Functions
	{
		/// Serialize
		public static System.String SerializeToString(System.Object data)
		{
			// make sr
			System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
			System.IO.StreamReader streamReader = null;

			// ret value
			System.String retValue = null;

			try
			{
				// make serializer
				System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(data.GetType());

				// serialize
				xmlSerializer.Serialize(memoryStream, data);

				// set pos to begining
				memoryStream.Flush();
				memoryStream.Position = 0;

				// create reader
				streamReader = new System.IO.StreamReader(memoryStream);

				// ok
				retValue = streamReader.ReadToEnd();
			}
			catch (System.Exception ex)
			{
				// throw
				throw
					new System.Exception(
						System.String.Format("Failed to serialize data type = {0}", data.GetType()),
						ex);
			}
			finally
			{
				// close stream
				memoryStream.Close();
				if (null != streamReader)
				{
					streamReader.Close();
				}
			}

			// done
			return retValue;
		}

		/// ToXmlDocument
		public static System.Xml.Linq.XDocument ToXDocument(System.Object data)
		{
			System.Xml.Linq.XDocument xDoc = System.Xml.Linq.XDocument.Parse(SerializeToString(data));
			return xDoc;
		}

		/// Load
		public static T Deserialize<T>(System.String objectXml)
		{
			// make sr
			System.IO.StringReader streamReader = new System.IO.StringReader(objectXml);

			// form meta
			T retValue;
			try
			{
				// open xml stream
				System.Xml.XmlReader xmlTextReader = System.Xml.XmlReader.Create(streamReader);

				// make serializer
				System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

				// deserialize the form ui
				retValue = (T)xmlSerializer.Deserialize(xmlTextReader);
			}
			catch (System.Exception ex)
			{
				// throw
				throw
					new System.Exception(
						System.String.Format("Failed to deserialize type = {0}, from {1}", typeof(T).FullName, objectXml),
						ex);
			}
			finally
			{
				// cose stream
				streamReader.Close();
			}

			// done
			return retValue;
		}
	}

}